<script>
import { useUserStore } from '../../stores/user'
import DeviceApi from '../../api/device'
import MyPagination from '@/components/MyPagination.vue'

export default {
  name: 'DeviceBookingList',
  components: {
    MyPagination,
  },
  data() {
    return {
      bookingList: [],
      total: 0,
      pageSize: 10,
      curPage: 1,
      loading: false,
      statusOptions: [
        { label: '全部', value: '' },
        { label: '待审核', value: 'pending' },
        { label: '已批准', value: 'approved' },
        { label: '已拒绝', value: 'rejected' },
        { label: '已完成', value: 'completed' }
      ],
      currentStatus: '',
      searchUserId: '',
      overdueDevices: [],
      showOverdueDialog: false
    }
  },
  computed: {
    isAdmin() {
      const userStore = useUserStore()
      return userStore.isAdmin
    }
  },
  methods: {
    async fetchBookingRecords() {
      this.loading = true
      try {
        const api = new DeviceApi()
        const params = {
          limit: this.pageSize,
          offset: (this.curPage - 1) * this.pageSize,
          status: this.currentStatus
        }
        
        if (this.isAdmin && this.searchUserId) {
          params.userId = this.searchUserId
        }

        const res = await api.getBookingRecords(params)
        if (res && res.data) {
          this.bookingList = res.data
          this.total = res.total || res.data.length
        }
      } catch (err) {
        console.error('获取预约记录失败:', err)
        this.$myMessageBox('获取预约记录失败')
      } finally {
        this.loading = false
      }
    },

    async handleStatusChange(record, newStatus) {
      try {
        const api = new DeviceApi()
        let response

        if (newStatus === 'completed') {
          // 如果是归还操作，使用归还接口
          response = await api.returnDevice({
            bookingId: record.id,
            returnNote: '管理员操作归还'
          })
        } else {
          // 其他状态更新使用状态更新接口
          response = await api.updateBookingStatus({
            deviceId: record.device_id,
            userId: record.user_id,
            status: newStatus
          })
        }
        
        if (response && response.code === 200) {
          this.$myMessageBox('操作成功')
          // 刷新列表以确保数据同步
          await this.fetchBookingRecords()
        } else {
          this.$myMessageBox(response.msg || '操作失败')
        }
      } catch (err) {
        console.error('操作失败:', err)
        this.$myMessageBox(err.response?.data?.msg || '操作失败，请稍后重试')
      }
    },

    handlePageChange(page) {
      this.curPage = page
      this.fetchBookingRecords()
    },

    handleStatusFilter(status) {
      this.currentStatus = status
      this.curPage = 1
      this.fetchBookingRecords()
    },

    handleSearch() {
      this.curPage = 1
      this.fetchBookingRecords()
    },

    async fetchOverdueDevices() {
      try {
        const api = new DeviceApi()
        const res = await api.getOverdueDevices()
        if (res && res.code === 200) {
          this.overdueDevices = res.data || []
          this.showOverdueDialog = true
        } else {
          this.$myMessageBox(res.msg || '获取超期设备失败')
        }
      } catch (err) {
        console.error('获取超期设备失败:', err)
        this.$myMessageBox(err.response?.data?.msg || '获取超期设备失败，请稍后重试')
      }
    },

    formatDate(dateString) {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
  },
  mounted() {
    this.fetchBookingRecords()
  }
}
</script>

<template>
  <div class="booking-list">
    <div class="header">
      <h2>设备预约记录</h2>
      <div class="filters">
        <div class="status-filter">
          <span>状态：</span>
          <select v-model="currentStatus" @change="handleStatusFilter(currentStatus)">
            <option v-for="option in statusOptions" 
                    :key="option.value" 
                    :value="option.value">
              {{ option.label }}
            </option>
          </select>
        </div>
        <div v-if="isAdmin" class="user-filter">
          <input type="text" 
                 v-model="searchUserId" 
                 placeholder="输入用户ID搜索"
                 @keyup.enter="handleSearch">
          <button @click="handleSearch">搜索</button>
          <button class="overdue-btn" @click="fetchOverdueDevices">查看超期设备</button>
        </div>
      </div>
    </div>

    <div class="booking-table" v-loading="loading">
      <table>
        <thead>
          <tr>
            <th>设备名称</th>
            <th>预约用户</th>
            <th>开始时间</th>
            <th>结束时间</th>
            <th>使用目的</th>
            <th>预约时间</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="record in bookingList" :key="record.id">
            <td>{{ record.device_title }}</td>
            <td>{{ record.username }}</td>
            <td>{{ new Date(record.start_time).toLocaleString() }}</td>
            <td>{{ new Date(record.end_time).toLocaleString() }}</td>
            <td>{{ record.purpose || '未填写' }}</td>
            <td>{{ new Date(record.borrow_time).toLocaleString() }}</td>
            <td>
              <span :class="['status-tag', record.status]">
                {{ 
                  record.status === 'pending' ? '待审核' :
                  record.status === 'approved' ? '已批准' :
                  record.status === 'rejected' ? '已拒绝' :
                  record.status === 'completed' ? '已完成' :
                  record.status === 'cancelled' ? '已取消' : record.status
                }}
              </span>
            </td>
            <td>
              <template v-if="isAdmin && record.status === 'pending'">
                <button class="btn-approve" 
                        @click="handleStatusChange(record, 'approved')">
                  批准
                </button>
                <button class="btn-reject" 
                        @click="handleStatusChange(record, 'rejected')">
                  拒绝
                </button>
              </template>
              <template v-if="record.status === 'approved'">
                <button class="btn-return" 
                        @click="handleStatusChange(record, 'completed')">
                  归还
                </button>
              </template>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="pagination">
      <my-pagination
        :total="total"
        :pageSize="pageSize"
        :curPage="curPage"
        @goto="handlePageChange"
        :showInfo="true"
      />
    </div>

    <div v-if="showOverdueDialog" class="overdue-dialog">
      <div class="overdue-dialog-content">
        <div class="dialog-header">
          <h3>超期未归还设备列表</h3>
          <button class="close-btn" @click="showOverdueDialog = false">&times;</button>
        </div>
        <div class="overdue-list">
          <div v-if="overdueDevices.length === 0" class="no-overdue">
            暂无超期未归还设备
          </div>
          <div v-else v-for="device in overdueDevices" :key="device.id" class="overdue-item">
            <div class="overdue-info">
              <h4>{{ device.device_title }}</h4>
              <p><strong>借用人：</strong>{{ device.username }}</p>
              <p><strong>开始时间：</strong>{{ formatDate(device.start_time) }}</p>
              <p><strong>结束时间：</strong>{{ formatDate(device.end_time) }}</p>
              <p><strong>超期天数：</strong>{{ Math.ceil((new Date() - new Date(device.end_time)) / (1000 * 60 * 60 * 24)) }}天</p>
            </div>
            <div class="overdue-actions">
              <button class="return-btn" @click="handleStatusChange(device, 'completed')">
                强制归还
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.booking-list {
  width: 95%;
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filters {
  display: flex;
  gap: 20px;
}

.status-filter select,
.user-filter input {
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-left: 8px;
}

.user-filter button {
  margin-left: 8px;
  padding: 8px 16px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.booking-table {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

th:nth-child(5) { width: 15%; } /* 预约时间 */
th:nth-child(6) { width: 8%; } /* 状态 */
th:nth-child(7) { width: 12%; } /* 操作 */

.status-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-tag.pending {
  background-color: #e6a23c;
  color: white;
}

.status-tag.approved {
  background-color: #28a745;
  color: white;
  min-width: 60px;
  text-align: center;
}

.status-tag.rejected {
  background-color: #f56c6c;
  color: white;
}

.status-tag.completed {
  background-color: #909399;
  color: white;
}

.status-tag.cancelled {
  background-color: #909399;
  color: white;
}

.btn-approve,
.btn-reject,
.btn-return {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 8px;
  min-width: 50px;
  text-align: center;
}

.btn-approve {
  background-color: #67c23a;
  color: white;
}

.btn-reject {
  background-color: #f56c6c;
  color: white;
}

.btn-return {
  background-color: #409eff;
  color: white;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.overdue-btn {
  margin-left: 10px;
  padding: 8px 16px;
  background-color: #ff4d4f;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.overdue-btn:hover {
  background-color: #ff7875;
}

.overdue-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.overdue-dialog-content {
  background: white;
  border-radius: 8px;
  width: 80%;
  max-width: 800px;
  max-height: 80vh;
  overflow-y: auto;
  padding: 20px;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.dialog-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  padding: 0;
}

.close-btn:hover {
  color: #666;
}

.overdue-list {
  display: grid;
  gap: 15px;
}

.overdue-item {
  background: #fff;
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.overdue-info h4 {
  margin: 0 0 10px 0;
  color: #333;
}

.overdue-info p {
  margin: 5px 0;
  color: #666;
}

.overdue-info strong {
  color: #333;
  margin-right: 5px;
}

.overdue-actions {
  display: flex;
  gap: 10px;
}

.no-overdue {
  text-align: center;
  padding: 20px;
  color: #999;
}

.return-btn {
  padding: 6px 12px;
  background-color: #ff4d4f;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.return-btn:hover {
  background-color: #ff7875;
}
</style> 